//
//  BindingPhoneCodeTableViewCell.m
//  customer
//
//  Created by 杨阳 on 2018/10/29.
//  Copyright © 2018 yinlong. All rights reserved.
//

#import "BindingPhoneCodeTableViewCell.h"
#import "MBProgressHUD.h"

@interface BindingPhoneCodeTableViewCell()

@property (nonatomic,strong) SsehConfigModel * sModel , * phoneModel;


@property(nonatomic,strong)NSDate *backDate;//进入后台时的时间

@property(nonatomic,strong)NSDate *frontDate;//重新打开应用时的时间

@end

@implementation BindingPhoneCodeTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.codeButton.layer.cornerRadius = 5;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setBackgroundTask) name:kRegisterBackgroundNoti object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setFrontTask) name:kRegisterFrontNoti object:nil];
}

- (void)setBackgroundTask{
    self.backDate = [NSDate date];
}

- (void)setFrontTask{
    self.frontDate = [NSDate date];
}


- (IBAction)codeButtonClick:(id)sender {
    
    if (k_Is_Empty(self.phoneModel.infoStr)) {
        [self showTipWithTitle:@"请输入手机号码"];
        return;
    }
    
    if (self.phoneModel.infoStr.length != 11) {
        [self showTipWithTitle:@"请输入11位手机号码"];
        return;
    }
    if (![self.sModel.infoStr1 isEqualToString:@"获取验证码"] && [self.sModel.infoStr1 integerValue]>0) {
        [self showErrorTipWithTitle:@"2分钟内不可重复发送!"];
        return;
    }
    if (_buttonClick) {
        _buttonClick((UIButton*)sender);
    }
    self.sModel.infoStr1 = @"120";
    [self getStartTime];
    
}

- (IBAction)tfEditingChanged:(id)sender {
    
    self.sModel.infoStr = self.tf.text;
    
}


-(void)configData:(SsehConfigModel *)model andPhoneModel:(SsehConfigModel *)phoneModel{
    self.sModel = model;
    self.phoneModel = phoneModel;
    self.tf.placeholder = model.placeHodleStr;
    [self.buttonClick setTitle:[NSString emptyStr:model.infoStr1] forState:UIControlStateNormal];
    
}

#pragma mark - 定时器
//开启定时器
- (void)getStartTime{
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     self.labelTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
     dispatch_source_set_timer(self.labelTimer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    AutoWeakSelf
     dispatch_source_set_event_handler(self.labelTimer, ^{
            NSInteger numTime = weakSelf.sModel.infoStr1.integerValue;
            numTime--;
            if(numTime<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(weakSelf.labelTimer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                    // 时间到，停止动作
                    [weakSelf destoryLabelTimer];
                    weakSelf.sModel.infoStr1 = @"获取验证码";
                    [weakSelf.codeButton setTitle:self.sModel.infoStr1 forState:UIControlStateNormal];
                    weakSelf.codeButton.userInteractionEnabled = YES;
                     });
             }else{
                       if (weakSelf.frontDate&&weakSelf.backDate) {   //这里面就是判断进出应用两次之间的时间差
                              NSTimeInterval backDate = [weakSelf.backDate timeIntervalSinceReferenceDate];
                              NSTimeInterval frontDate = [weakSelf.frontDate timeIntervalSinceReferenceDate];
                              int interval = frontDate - backDate;
                              numTime = numTime - interval;
                              weakSelf.backDate = nil;
                              weakSelf.frontDate = nil;
                       }
                     NSInteger seconds = numTime % 121;
                     dispatch_async(dispatch_get_main_queue(), ^{
                     //每秒执行一次
                    weakSelf.sModel.infoStr1 = [NSString stringWithFormat:@"%ld",seconds];
                    weakSelf.codeButton.userInteractionEnabled = NO;
                    [weakSelf.codeButton setTitle:weakSelf.sModel.infoStr1 forState:UIControlStateNormal];
                });
               
                }
            });
        dispatch_resume(weakSelf.labelTimer);
}

//销毁定时器
- (void)destoryLabelTimer{
    if (_labelTimer) {
        _labelTimer = nil;
    }
}

- (void)showTipWithTitle:(NSString*)title {
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = title;
    hud.contentColor = [UIColor whiteColor];
    hud.bezelView.backgroundColor = [UIColor blackColor];
    [[UIApplication sharedApplication].keyWindow addSubview:hud];
    [hud showAnimated:YES];
    [hud hideAnimated:YES afterDelay:1.0f];
}

- (void)showErrorTipWithTitle:(NSString*)title {
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.label.text = title;
    hud.contentColor = [UIColor whiteColor];
    hud.customView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"closeNet"]];
    hud.bezelView.backgroundColor = [UIColor blackColor];
    [[UIApplication sharedApplication].keyWindow addSubview:hud];
    [hud showAnimated:YES];
    [hud hideAnimated:YES afterDelay:1.0f];
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
